<template>
  <div class="app-container">
    <el-form
      ref="formData"
      :model="formData"
      :rules="rules"
      :inline="true"
      class="demo-form-inline"
      size="small"
      label-position="right"
    >
      <el-row>
        <el-col :span="16">
          <el-form-item label="爬虫名称:" prop="author">
            <el-input
              v-model="formData.author"
              placeholder="请输入爬虫名称"
              clearable
              @blur="blurVerifiedFun"
              @focus="focusVerifiedFun"
              @clear="clearVerifiedFun"
            />
          </el-form-item>
          <el-form-item>
            <span style="display: flex;">
              <!--图标来源：https://icons8.com/-->
              <img v-if="isShowVerified" :src="lloading" style="width: 25px; height: 25px; margin-top: 3px;">
              <img v-if="isVerifiedSuccess" :src="ssuccess" style="width: 25px; height: 25px; margin-top: 3px;">
              <span v-if="isVerifiedFaild" style="color: red;">
                爬虫不存在
              </span>
            </span>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="5">
          <el-form-item label="数据库表:" prop="tableName">
            <el-select
              v-model="formData.tableName"
              clearable
              placeholder="请选择数据表"
            >
              <el-option
                v-for="item in tableList"
                :key="item.name"
                :label="item.name"
                :value="item.name"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="8">
          <el-form-item label="发布时间:">
            <div class="block">
              <el-date-picker
                v-model="formData.pubtime"
                type="datetimerange"
                align="center"
                value-format="yyyy-MM-dd"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :default-time="['00:00:00', '23:59:59']"
              />
            </div>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="8">
          <el-form-item label="入库时间:">
            <div class="block">
              <el-date-picker
                v-model="formData.addTime"
                type="datetimerange"
                align="center"
                value-format="yyyy-MM-dd HH:mm:ss"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :default-time="['00:00:00', '23:59:59']"
              />
            </div>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="10" style=" margin-bottom: 8px;">
        <el-col :span="1.5">
          <el-button ref="fetchData" icon="el-icon-search" type="primary" size="mini" @click="fetchData">查询数据</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button ref="resetData" icon="el-icon-refresh" type="primary" size="mini" @click="resetData">重置数据</el-button>
        </el-col>
        <el-col :span="20">
          <span style="color:#999; display: flex; margin-top: 10px;">
            (注：此处的查询是从es获取的数据id，即有可能mysql入库了，但是es尚未清洗，故可能出现查询不到的情况，此为正常情况)
          </span>
        </el-col>
      </el-row>
    </el-form>

    <!--列表 height="600"-->
    <el-table
      ref="tableList"
      v-loading="loading"
      :data="list"
      :header-cell-style="headStyle"
      :cell-style="cellStyle"
      :default-sort="{prop: 'addTimeMysql', order: 'descending'}"
      @sort-change="handleSortChange"
    >
      <el-table-column prop="dataId" label="数据ID" width="120" align="center" />
      <el-table-column prop="title" label="标题" align="center" />
      <el-table-column prop="cateId" label="分类" width="100" align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.cateId == 1">招标</span>
          <span v-else-if="scope.row.cateId == 2">中标</span>
          <span v-else-if="scope.row.cateId == 3">开标</span>
          <span v-else>其他</span>
        </template>
      </el-table-column>
      <el-table-column prop="author" label="来源" width="200" :show-overflow-tooltip="true" align="center" />
      <el-table-column prop="location" label="来源地区" width="100" align="center" />
      <el-table-column prop="pubtime" label="发布时间" width="165" sortable="custom" align="center" />
      <el-table-column prop="addTimeMysql" label="mysql入库时间" width="180" sortable="custom" align="center" />
      <el-table-column prop="addTimeEs" label="es入库时间" width="180" sortable="custom" align="center" />
      <el-table-column label="正文" width="100" align="center">
        <template slot-scope="scope">
          <el-button v-if="scope.row.info != ''" ref="yulan" type="primary" icon plain size="mini" @click="previewHtml2(scope.row)">
            <svg-icon icon-class="view-fill" style="margin-right: 3px; width: 15px; height: 15px" />
            预览
          </el-button>
          <span v-else>
            正文为空
          </span>
        </template>
      </el-table-column>

      <el-table-column prop="outurl" label="链接" width="100" align="center">
        <template slot-scope="scope">
          <el-button v-if="scope.row.outurl != ''" ref="linkOut" type="primary" plain size="mini" icon @click="linkOut(scope.row.outurl)">
            <svg-icon icon-class="link" style="margin-right: 5px; width: 12px; height: 12px" />
            跳转
          </el-button>
          <span v-else>
            链接为空
          </span>
        </template>
      </el-table-column>

      <el-table-column prop="intro" label="附件" width="100" align="center">
        <template slot-scope="scope">
          <el-button v-if="scope.row.intro != ''" type="primary" icon plain size="mini" @click="downloadFile(scope.row.fileList)">
            <svg-icon icon-class="download1" style="margin-right: 3px; width: 15px; height: 15px" />
            下载
          </el-button>
          <span v-else>
            附件为空
          </span>
        </template>
      </el-table-column>

    </el-table>

    <!-- 分页组件 -->
    <div style="display: flex; justify-content: center; align-items: center;">
      <span style="font-size: 14px; color: rgb(84 81 81); margin-right: 5px;">共 {{ totalNum }} 条记录</span>
      <el-pagination
        background
        :current-page="page"
        :total="total"
        :page-size="limit"
        :page-sizes="[10]"
        prev-text="上一页"
        next-text="下一页"
        style="padding: 30px 0; text-align: center"
        layout="sizes, prev, pager, next, jumper"
        @size-change="changePageSize"
        @current-change="changeCurrentPage"
      />
    </div>

    <!-- 弹窗模板 -->
    <modal name="showData-modal">
      <h2 style="font-size: 20px; text-align: center;">预览</h2>
      <!-- iframe 内容 -->
      <iframe :srcdoc="iframeContent" />
    </modal>

    <!-- 下载弹窗 -->
    <modal name="download-modal">
      <h2 style="font-size: 20px; text-align: center;">附件</h2>
      <!-- 分割线 -->
      <div class="separator" />
      <!-- table 内容 -->
      <div class="fileTableClass">
        <el-table
          ref="downLoadList"
          :data="downloadFiles"
          border
          stripe
          :header-cell-style="headStyle"
          :cell-style="cellStyle2"
        >
          <el-table-column label="序号" width="50">
            <template slot-scope="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column prop="fileName" label="文件名称" align="center" />
          <el-table-column prop="fileTime" label="首次上传时间" width="180" align="center" />
          <el-table-column prop="fileType" label="文件类型" width="80" align="center" />
          <el-table-column label="操作" width="80">
            <template slot-scope="scope">
              <el-button ref="openDownloadButton" size="mini" icon @click="openDownload(scope.row.fileUrl)">
                预览
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </modal>

  </div>

</template>
<script>
import variables from '@/styles/variables.scss'
// import { MessageBox } from 'element-ui'
import crawlerDetailApi from '@/api/crawler/crawlerDetail'
import lloading from '@/icons/gif/loading.gif'
import ssuccess from '@/icons/gif/success.png'
import ffail from '@/icons/gif/delete.png'
import crawler from '@/api/crawler/crawler'

export default {
  name: 'ShowData',
  data() {
    return {
      lloading: lloading,
      ssuccess: ssuccess,
      ffail: ffail,
      isShowVerified: false,
      isVerifiedSuccess: false,
      isVerifiedFaild: false,
      total: 0, // 总条数1000，为了让翻页按钮只显示100页
      totalNum: 0, // 数据库总记录数
      page: 1, // 默认页码
      limit: 10, // 每页记录数
      formData: { // 表单数据
        author: '',
        tableName: '',
        pubtime: [],
        addTime: [],
        orderBys: {
          order: 'DESC',
          orderColumn: 'addTimeMysql'
        }
      },
      loading: true,
      isLoading: true,
      isValid: true,
      list: [], // 列表数据
      downloadFiles: [], // 附件列表
      iframeContent: '', // info
      tableList: [
        {
          name: 'stang_bid_new'
        },
        {
          name: 'stang_cbid'
        }
      ],
      rules: {
        author: {
          required: true,
          message: '不能为空',
          trigger: 'blur'
        },
        tableName: {
          required: true,
          message: '不能为空',
          trigger: 'blur'
        }
      }
    }
  },

  created() {
    if (this.formData.author === '' || this.formData.tableName === '') {
      this.loading = false
    } else {
      this.fetchData()
    }
  },

  methods: {
    fetchData() {
      this.$refs.formData.validate((err) => {
        // true表示校验通过, false表示校验失败
        if (!err) {
          this.$message({
            message: '参数缺失',
            type: 'warning'
          })
          this.loading = false
        } else if (this.isVerifiedFaild) {
          this.$message({
            message: '爬虫不存在',
            type: 'warning'
          })
        } else {
          this.loading = true
          const searchData = {
            page: this.page,
            limit: this.limit,
            tableName: this.formData.tableName,
            author: this.formData.author,
            pubtimeStart: this.formData.pubtime[0],
            pubtimeEnd: this.formData.pubtime[1],
            addTimeStart: this.formData.addTime[0],
            addTimeEnd: this.formData.addTime[1],
            orderBys: this.formData.orderBys
          }
          return crawlerDetailApi.listPageCrawlerData(searchData).then((response) => {
            if (response.code === 200) {
              this.list = response.data.result.list
              this.totalNum = response.data.result.total
              this.total = 1000
              this.loading = false
            }
          }).catch((reason) => {
            this.loading = false
          })
        }
      })
      this.$nextTick(() => {
        this.$refs.fetchData.$el.blur()
      })
    },

    // 获得焦点时展示动态加载图标
    focusVerifiedFun() {
      this.isVerifiedSuccess = false
      this.isVerifiedFaild = false
      this.isShowVerified = true
    },

    // 失去焦点时校验来源名称
    blurVerifiedFun() {
      if (this.formData.author) {
        crawler.verifiedAuthor(this.formData.author).then((response) => {
          if (response.code === 200) {
            this.isShowVerified = false
            if (response.data.isVerified) {
              this.isVerifiedSuccess = true
            } else {
              this.isVerifiedFaild = true
            }
          }
        })
      } else {
        this.isVerifiedSuccess = false
        this.isVerifiedFaild = false
        this.isShowVerified = false
      }
    },

    // 点击clear时触发
    clearVerifiedFun() {
      this.isVerifiedSuccess = false
      this.isVerifiedFaild = false
      this.isShowVerified = false
    },

    // 预览正文弹窗
    previewHtml2(row) {
      if (row.info === '') {
        this.$message({
          message: 'info为空',
          type: 'warning'
        })
      } else {
        this.iframeContent = row.info
        this.$modal.show('showData-modal')

        // MessageBox.alert(row.info, '预览', {
        //   dangerouslyUseHTMLString: true, // 允许html文本
        //   closeOnClickModal: true, // 允许点击空白处关闭弹窗
        //   customClass: 'custom-box' // css样式
        // })
      }
      this.$nextTick(() => {
        this.$refs.yulan.$el.blur()
      })
    },

    // 跳转链接
    linkOut(outurl) {
      window.open(outurl, '_blank', 'noreferrer,noopener')
      this.$nextTick(() => {
        this.$refs.linkOut.$el.blur()
      })
    },

    // 附件下载
    downloadFile(fileList) {
      this.downloadFiles = fileList
      this.$modal.show('download-modal')
    },

    // 打开附件链接窗口下载
    openDownload(url) {
      window.open(url + '?download=0')
      this.$nextTick(() => {
        this.$refs.openDownloadButton.$el.blur()
      })
    },

    // 触发排序
    handleSortChange({ order, prop }) {
      // (单列排序)
      this.formData.orderBys.orderColumn = prop
      if (order === 'ascending') {
        this.formData.orderBys.order = 'ASC'
      } else if (order === 'descending') {
        this.formData.orderBys.order = 'DESC'
      } else {
        this.formData.orderBys.orderColumn = ''
        this.formData.orderBys.order = ''
      }
      this.page = 1
      this.fetchData()
    },

    resetData() {
      this.formData = {
        author: '',
        tableName: '',
        pubtime: [],
        addTime: [],
        orderBys: {
          order: 'DESC',
          orderColumn: 'addTimeMysql'
        }
      }
      this.page = 1
      this.limit = 10
      this.$refs.tableList.sort('addTimeMysql', 'descending')
      this.$nextTick(() => {
        this.$refs.resetData.$el.blur()
      })
    },

    // 每页展示条数的改变，size：回调函数, 表示当前选中的展示条数
    changePageSize(size) {
      this.limit = size
      this.fetchData()
    },

    // 翻页，page：回调函数, 表示当前选中的页码
    changeCurrentPage(page) {
      this.page = page
      this.fetchData()
    },

    // 表头style
    headStyle() {
      return 'color: black; backgroundColor: ' + variables.globalStyle
    },

    // 列style
    cellStyle({ row, column, rowIndex, columnIndex }) {
      if (row.isTop === 1) {
        return 'backgroundColor: #f2f2f2; height: 50px'
      } else {
        return 'height: 50px'
      }
    }
  }
}
</script>

<style>
.vm--modal {
  top: 80px !important;
  left: 500px !important;
  height: 800px !important;
  width: 1000px !important;
}
iframe {
  height: 745px;
  width: 1002px;
  margin-left: -2px;
}
</style>
